package com.icesoft.core.web.suppose.token.filter;

import com.icesoft.core.common.helper.Resp;
import com.icesoft.core.common.helper.RespCode;
import com.icesoft.core.web.base.BaseAnnotationInterceptor;
import com.icesoft.core.web.excption.HttpErrorCodeEnum;
import com.icesoft.core.web.helper.ResponseUtils;
import com.icesoft.core.web.suppose.token.AuthTokenCheck;
import com.icesoft.core.web.suppose.token.IAuthToken;
import com.icesoft.core.web.suppose.token.service.IAuthTokenService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class RequiredAuthTokenFilter extends BaseAnnotationInterceptor<AuthTokenCheck> {
    private static final String AUTH_TOKEN_NAME = "token";
    public static final String ATTRIBUTE_AUTH_TOKEN = "auth_token";
    private IAuthTokenService tokenUserService;

    public RequiredAuthTokenFilter(ObjectProvider<IAuthTokenService> tokenServiceObjectProvider) {
        this.tokenUserService = tokenServiceObjectProvider.getIfAvailable();
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, HandlerMethod handlerMethod, AuthTokenCheck annotation) {
        if (annotation.disable()) {
            return true;
        }
        if (tokenUserService == null) {
            log.trace("tokenUserService is not found");
            return true;
        }
        String token = request.getHeader(AUTH_TOKEN_NAME);
        if (token == null) {
            token = request.getParameter(AUTH_TOKEN_NAME);
        }
        if (StringUtils.isEmpty(token)) {
            log.error("请求{},缺少请求头：token", request.getRequestURI());
            ResponseUtils.writeJson(response, Resp.error("用户信息为空").code(RespCode.NO_PERMISSION));
            return false;
        }
        if (tokenUserService.isTokenExpired(token)) {
            log.debug("请求{}，token={}已过期", request.getRequestURI(), token);
            ResponseUtils.writeJson(response, HttpErrorCodeEnum.TOKEN_EXPIRED.toResp());
            return false;
        }
        IAuthToken authToken = tokenUserService.findByToken(token);
        if (authToken == null) {
            log.debug("请求{}，token={}无效", request.getRequestURI(), token);
            ResponseUtils.writeJson(response, Resp.error("无效用户").code(RespCode.NO_PERMISSION));
            return false;
        }
        if (!tokenUserService.isAuthTokenEnable(authToken)) {
            log.debug("请求{}，token={}不可用", request.getRequestURI(), token);
            ResponseUtils.writeJson(response, HttpErrorCodeEnum.ACCESS_DENY.toResp());
            return false;
        }
        request.setAttribute(ATTRIBUTE_AUTH_TOKEN, authToken);
        return true;
    }
}
